#!/usr/bin/env python
# -*- coding: utf-8 -*-
#       
#       Copyright 2010 Santiago Lezica, Juan Pablo Orsay, Facundo Martinez.
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

from carcassonne.model import CommObject
from twisted.internet.protocol import Factory, Protocol

class ServerProtocol(Protocol):

    def connectionMade(self):
        self.factory.connectionMade(self)

    def connectionLost(self, reason):
        self.factory.connectionLost(self)

    def dataReceived(self, data):
        self.factory.dataReceived(self, data)

    def sendData(self, data):
        self.transport.write(data)


class ServerFactory(CommObject, Factory):

    protocol = ServerProtocol

    def __init__(self, handler = None):
        self.handler = handler
        self._idcount = 100 # IDs lower than 100 are reserved. What for? No idea
        self._clients = {}

    def getClients(self):
        return self._clients.keys()

    def connectionMade(self, client):
        self._idcount += 1
        client._id = self._idcount
        self._clients[self._idcount] = client

    def connectionLost(self, client):
        del self._clients[client._id]

    def dataReceived(self, client, data):
        self.handler.handle(client._id, data)

    def sendData(self, id, data):
        if id in self._clients:
            self._clients[id].sendData(data)

    def config(self, handler = None):
        self.handler = handler or self.handler
